const express = require('express');
const router = express.Router();
// const {
//   queryByPhone,
//   queryByPhoneAndPassword,
// } = require("@controller/user.js");
const { fetchList } = require('../../../controllers/order');
const { queryAll, queryById } = require('@dao/movieDao.js');
const tokenAuth = require('@middleware/tokenAuth.js');
const path = require('path');
const fs = require('fs');
const { openSync } = require('fs');
const URL = require('url');

//got 不支持 require
// import got from "got";
// const got = require("got");
const got = import('got');

const barcode = require('@util/barcode');

const { downloadFn } = require('./../1');

// router.post("/register", queryByPhone, (err, req, res, next) => {
//   console.log(err, "[--");
//   if (err) {
//     res.json(err);
//   }
// });

// 登录并使用 JWT 签名返回 token
// router.post("/login", queryByPhoneAndPassword, async (err, req, res, next) => {
//   if (err) {
//     res.json(err);
//   }
// });

router.get('/movie', tokenAuth, async (err, req, res, next) => {
  console.log(err, '[-----');
  if (err.code !== 200) {
    res.json(err);
  } else {
    try {
      const movies = await queryAll();
      res.json({
        code: 200,
        msg: '成功~',
        data: movies,
      });
    } catch (error) {
      res.json({
        code: 500,
        msg: error.message,
      });
    }
  }
});

// 为了实现前端校验用户，后端需要在用户登录的时候记录下该用户的状态并加密之后返回给前端。之后该用户的所有请求都应该附带这个加密后的状态，后端取到这个状态解密，并与之前保存的状态对比，以此来判断该用户是否登录或合法。
router.get('/validate', (req, res) => {
  const token = req.headers.authorization; // 在请求头中附带token信息
  jwt.verify(token, secret, (err, decode) => {
    // 验证token是否合法
    if (err) {
      return res.json({
        code: 1,
        data: '当前token无效',
      });
    }
    // 如果验证合法，重新生成新的token，并返回信息
    res.json({
      username: decode.username,
      code: 0,
      token: jwt.sign({ username: 'admin' }, secret, {
        expiresIn: 20,
      }),
    });
  });
});

// 动态路径
router.get('/movie/:mid', tokenAuth, async (err, req, res, next) => {
  const { mid } = req.params || {};
  if (err.code !== 200) {
    res.json(err);
  } else {
    try {
      const movies = await queryById(mid);
      res.json({
        code: 200,
        msg: '成功~',
        data: movies,
      });
    } catch (error) {
      res.json({
        code: 500,
        msg: error.message,
      });
    }
  }
});

// 设置响应报文头实现下载
// 实现下载一般就是通过浏览器点击下载

// 后台一般设置一下响应头，有下面两种方式

// Content-Type
// Content-Disposition
router.get('/download/:type', async (req, res, next) => {
  const { type } = req.params || {};
  const { url } = req.query || {};
  // const link = new URL(url)
  // console.log(typeof type);
  console.log(path.parse(url));
  const { dir, base } = path.parse(url);
  // const fd = fs.openSync(url)
  // if (type === "1") {
  res.setHeader('Content-Type', 'application/octet-stream');
  // } else if (type === "2") {
  res.setHeader('Content-Disposition', `attachment;filename=${base}`);
  const fileStream = await got(url).buffer();
  console.log(fileStream);
  // fileStream.on("data", (data) => {
  res.write(fileStream, 'binary');
  // })
  // fileStream.on("end", () => {
  res.end();
  // })
  // res.sendFile(url)
  // } else {
  // res.json({
  //   code: 404,
  // });
  // }
});

router.get('/order', fetchList);

router.get('/download', (req, res, next) => {
  res.download('./public/' + req.body.files, req.body.files, (err) => {
    if (err) {
      res.send('上传失败！');
    } else {
      console.log('上传成功！');
    }
  });
});

router.post('/upload', (req, res, next) => {
  const { file } = req.body;
  if (file) {
    const base64 = file.replace(/^data:image\/\w+;base64,/, '');
    const bitmap = new Buffer.from(base64, 'base64');
    fs.writeFile(
      path.resolve(__dirname, '../../../temp', 'image.png'),
      bitmap,
      (err) => {
        if (err) {
          res.json({
            code: 500,
            msg: err.message,
          });
        } else {
          res.json({
            code: 200,
            msg: '保存成功！',
          });
        }
      }
    );
  } else {
    res.json({
      code: 4001,
      msg: '缺少参数',
    });
  }
  console.log(req.body);
});

router.post('/barcode', (req, res, next) => {
  const { url } = req.body || {};
  console.log(req.body);
  barcode(url);
});

router.get('/static', downloadFn, (req, res, next) => {
  res.json({ code: 200 });
});

module.exports = router;
